package com.centaline.androidsalesblog.base;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.PermissionChecker;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;

import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.widgets.SpeechDialog;
import com.centanet.framework.widget.MaterialSearchView;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechRecognizer;
import com.orhanobut.logger.Logger;

/**
 * 委托搜索小区基类
 */
public abstract class BaseEstateSearchActivity extends BaseActivity implements MaterialSearchView.OnQueryTextListener,
        MaterialSearchView.VoiceClick {

    protected static final int REQ_AUDIO_RECORD = 102;
    protected String[] permissions = new String[]{Manifest.permission.RECORD_AUDIO};

    protected MaterialSearchView searchView;
    protected RecyclerView rv_distance;
    protected AppCompatTextView atv_distance;

    protected SpeechDialog speechDialog;

    protected SpeechRecognizer speechRecognizer;

    private InitListener initListener = new InitListener() {
        @Override
        public void onInit(int code) {
            if (code != ErrorCode.SUCCESS) {
                Logger.d("Speech init error : %d", code);
            }
        }
    };

    private View.OnTouchListener onTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (MotionEvent.ACTION_DOWN == event.getAction())
                setImeVisibility(false);
            return false;
        }
    };

    @Override
    protected void findViews() {
        setUniversalToolbar();
        rv_distance = (RecyclerView) findViewById(R.id.rv_distance);
        atv_distance = (AppCompatTextView) findViewById(R.id.atv_distance);
    }

    @Override
    protected void initViews() {
        rv_distance.setLayoutManager(new LinearLayoutManager(this));
        rv_distance.setOnTouchListener(onTouchListener);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (speechRecognizer.isListening()) {
            speechRecognizer.cancel();
        }
        speechRecognizer.destroy();
    }

    /**
     * 初始化语音
     */
    protected void initSpeech(Context context) {
        speechRecognizer = SpeechRecognizer.createRecognizer(context, initListener);
        speechRecognizer.setParameter(SpeechConstant.DOMAIN, "iat");
        speechRecognizer.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
        speechRecognizer.setParameter(SpeechConstant.ACCENT, "mandarin");
        // 设置听写引擎
        speechRecognizer.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);
        // 设置返回结果格式
        speechRecognizer.setParameter(SpeechConstant.RESULT_TYPE, "json");

        // 设置语音前端点:静音超时时间，即用户多长时间不说话则当做超时处理
        speechRecognizer.setParameter(SpeechConstant.VAD_BOS, "3000");
        // 设置语音后端点:后端点静音检测时间，即用户停止说话多长时间内即认为不再输入， 自动停止录音
        speechRecognizer.setParameter(SpeechConstant.VAD_EOS, "500");
        // 设置标点符号,设置为"0"返回结果无标点,设置为"1"返回结果有标点
        speechRecognizer.setParameter(SpeechConstant.ASR_PTT, "0");

        speechDialog = new SpeechDialog(this, speechRecognizer, new SpeechDialog.SpeechResult() {
            @Override
            public void result(String result) {
                setQuery(result, false);
            }
        });
    }

    protected void setQueryHint(CharSequence hint) {
        if (searchView != null)
            searchView.setQueryHint(hint);
    }

    /**
     * 设置输入法状态
     */
    protected void setImeVisibility(boolean visibility) {
        if (searchView != null)
            searchView.setImeVisibility(visibility);
    }

    /**
     * 设置搜索内容
     *
     * @param submit 是否提交
     */
    protected void setQuery(CharSequence query, boolean submit) {
        if (searchView != null)
            searchView.setQuery(query, submit);
    }

    /**
     * 立即执行textChanged
     */
    protected void textChangedImmediately() {
        if (searchView != null)
            searchView.textChangedImmediately();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_search, menu);
        searchView = (MaterialSearchView) menu.findItem(R.id.action_search).getActionView();
        searchView.setImeVisibility(true);
        searchView.setOnQueryTextListener(this);
        searchView.setVoiceClick(this);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public void voiceClick() {
        if (checkRecordAudioPermission()) {
            speechDialog.show();
        }
    }

    /**
     * 检查音频录制权限
     */
    protected boolean checkRecordAudioPermission() {
        if (PermissionChecker.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
            setImeVisibility(false);
            if (ActivityCompat.shouldShowRequestPermissionRationale(getActivityForPermissions(), Manifest.permission.RECORD_AUDIO)) {
                new AlertDialog.Builder(this)
                        .setTitle(R.string.permission_title)
                        .setMessage("麦克风:将您的说话内容快速转化为文字并进行房源搜索.")
                        .setPositiveButton("立即获取", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                requestRecordAudioPermission();
                            }
                        })
                        .setNegativeButton("下次再说", null)
                        .create()
                        .show();
            } else {
                requestRecordAudioPermission();
            }
            return false;
        } else {
            return true;
        }
    }

    /**
     * 获取申请权限的Activity
     */
    protected abstract Activity getActivityForPermissions();

    /**
     * 申请录音权限
     */
    private void requestRecordAudioPermission() {
        ActivityCompat.requestPermissions(getActivityForPermissions(), permissions, REQ_AUDIO_RECORD);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQ_AUDIO_RECORD:
                if (PackageManager.PERMISSION_GRANTED == grantResults[0]) {
                    setImeVisibility(false);
                    speechDialog.show();
                } else {
                    setImeVisibility(false);
                    new AlertDialog.Builder(this)
                            .setTitle("您拒绝了麦克风使用权限")
                            .setMessage(R.string.permission_refuse)
                            .setPositiveButton(R.string.set, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    startPermissionSetting();
                                }
                            })
                            .setNegativeButton("下次再说", null)
                            .create()
                            .show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
                break;
        }
    }
}
